<template>
  <div class="attGroupDialog">
    <!-- 添加编辑考勤组 -->
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleDialogClose">
    <div class="workbench-editor">
      <div class="form-content">
        <el-form
          ref="dataform"
          :model="dataform"
          label-width="120px"
          :rules="rules"
        >
          <el-form-item label="考勤组名称:" prop="attendanceGroup.name">
            <el-input
              v-model="dataform.attendanceGroup.name"
              placeholder="请输入内容"
              style="width: 50%"
            />
          </el-form-item>
          <el-form-item label="参与考勤人员:" prop="pepId">
            <el-button @click="openPersonnel()">
              <span v-if="dataform.pepId.length == 0">请选择 ></span>
              <span v-else>共{{ dataform.pepId.length }}人 ></span>
            </el-button>
          </el-form-item>
          <el-form-item label="考勤类型:" prop="attendanceGroup.type">
            <div class="type-radio">
              <el-radio
                v-model="dataform.attendanceGroup.type"
                :label="1"
                @change="adgType"
              >
                <span>固定班制（每天考勤时间一样）</span>
                <div style="color: #ccc; margin-left: 11%">
                  适用于：固定上班时间制的员工
                </div>
              </el-radio>
            </div>
            <div class="type-radio">
              <el-radio
                v-model="dataform.attendanceGroup.type"
                :label="2"
                @change="adgType"
              >
                <span>大小周制</span>
                <div style="color: #ccc; margin-left: 11%">
                  适用于：大小周工作制的员工
                </div>
              </el-radio>
            <!-- 大小周开关 -->
              <!-- <el-switch
                v-if="dataform.attendanceGroup.type == 2"
                v-model="dataform.attendanceGroup.weekType"
                :active-value="1"
                :inactive-value="2"
                active-color="#13ce66"
                inactive-color="#AAAAAA"
                class="type-switch"
                @change="setweekType"
              /> -->
              <!-- <div
                v-if="dataform.attendanceGroup.type == 2"
                class="type-switch-text"
              >
                <span v-if="dataform.attendanceGroup.weekType == 1">大>小</span>
                <span v-if="dataform.attendanceGroup.weekType == 2">小>大</span>
              </div>
              <div
                v-if="dataform.attendanceGroup.type == 2"
                class="type-switch-tips"
              >
                初始本年大小周顺序
              </div> -->
            </div>
          </el-form-item>
          <el-form-item label="考勤时间段:" required>
            <el-row type="flex" class="row-bg" justify="space-around">
              <el-col :span="24">
                <span>9:00-12:30,14:00-18:00</span>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="休息日选择:" prop="attendanceGroup.offday">
            <el-checkbox-group
              v-model="dataform.attendanceGroup.offday"
              @change="clickWeek"
            >
              <el-checkbox :label="1">周一</el-checkbox>
              <el-checkbox :label="2">周二</el-checkbox>
              <el-checkbox :label="3">周三</el-checkbox>
              <el-checkbox :label="4">周四</el-checkbox>
              <el-checkbox :label="5">周五</el-checkbox>
              <el-checkbox :label="6">周六</el-checkbox>
              <el-checkbox :label="0">周日</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label-width="0px">
            <el-row>
              <el-col :span="22" :offset="1">
                <ele-calendar
                  :render-content="renderContent"
                  :data="datedef"
                  :prop="dateprop"
                  value-format="yyyy-MM-dd"
                  border
                />
              </el-col>
            </el-row>
          </el-form-item>
          <div class="we-bottom-btn">
            <el-button type="primary" @click="postAttGroup('dataform')">确定</el-button>
        </div>
        </el-form>

      </div>
    </div>
  </el-dialog>
    <div class="chooseUsers">
        <!-- 多选人员弹窗 -->
        <el-dialog
          title="选择员工"
          :visible.sync="chooseDialogVisible"
          :close-on-click-modal="false"
          width="700px"
          :before-close="closeStaffDialog"
        >
          <div>
            <el-row>
              <el-col :span="12" class="bor-rig">
                <el-input
                  v-model="filterText"
                  placeholder="输入关键字进行过滤"
                />
                <div class="tree-height">
                  <el-tree
                    ref="tree"
                    :data="UserData"
                    show-checkbox
                    node-key="id"
                    highlight-current
                    @check-change="handleCheckChange"
                  />
                </div>
              </el-col>
              <el-col :span="12" class="bor-lef">
                <div style="line-height: 35px">已选人员</div>
                <div class="tree-height">
                  <el-row :gutter="5">
                    <el-col
                      v-for="(item, index) in showCheckList"
                      :key="index"
                      :span="8"
                    >
                      <div class="show-check">
                        <span v-if="item.name">{{ item.name }}</span>
                        <span v-else>{{ item.peopleName }}</span>
                        <i
                          class="el-icon-close red"
                          @click="closeCheckTree(index)"
                        />
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </el-col>
            </el-row>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="closeStaffDialog">取 消</el-button>
            <el-button type="primary" @click="postDialog2">保 存</el-button>
          </span>
        </el-dialog>
        <!-- 提示换组弹窗 -->
        <add-dialog
          :title="tipTitle"
          :dialogvisible="changeDialog"
          @closeDialog="cancelAddTo"
          @determine="determineAdd"
        >
          <template v-slot:add-content>
            <p class="deleteUser">{{ tipDialog.dialogMsg }}</p>
          </template>
        </add-dialog>
  </div>
  </div>
</template>

<script>
import eleCalendar from 'ele-calendar';
import addDialog from "@/views/components/addDialog";
import 'ele-calendar/dist/vue-calendar.css'
import { getDate } from '@/util/dateUtil.js';
export default {
  name: "AttGroupDialog",
  components: {
    eleCalendar,
    addDialog,
  },
  props: {
    dialogVisible: Boolean,
    dialogTitle: String,
    dataform: Object,
    datedef: Array,
    dateprop: String,
    dialogType: Number
  },
  data() {
    return {
      chooseDialogVisible: false, // 多选人员弹窗开关
      filterText: '', // 树状图搜索
      showCheckList: [], // 选中人员展示
      tipTitle: '提示', // 换组提示弹窗标题
      changeDialog: false, // 换组提示弹窗开关
      // 换组提示弹窗相关数据
      tipDialog: {
        userIds: [],
        dialogMsg: '' // 换组提示弹窗提示消息
      },
      UserData: [], // 人员树状图
      rules: {
        pepId: [
          { required: true, message: "请选择考勤人员", trigger: "change" },
        ],
        "attendanceGroup.name": [
          { required: true, message: "请输入考勤组名称", trigger: "blur" },
          { max: 8, message: "最多输入8个字符", trigger: "blur" },
        ],
        "attendanceGroup.type": [
          { required: true, message: "请选择考勤类型", trigger: "change" },
        ],
        "attendanceGroup.offday": [
          { required: true, message: "请选择休息日", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 添加编辑考勤组弹窗关闭按钮
    handleDialogClose() {
      this.$emit('canceladd');
      this.$refs["dataform"].resetFields();
      this.dataform.attendanceGroup.id = null;
      this.dataform.attendanceGroup.name = '';
      this.dataform.pepGroup = [];
      this.dataform.pepId = [];
    },
    // 多选人员弹窗
    async openPersonnel() {
      let type = this.dialogType;
      let res = await this.$http.get("/user/list", {
        params: {
          pageNum: 1,
          pageSize: 100,
        },
      });
      res.data.list.forEach(element => {
        element.label = element.username;
        delete element.username;
      });
      this.UserData = res.data.list;
      let that = this;
      let ids = [];

      if (type == 1) {
        this.dataform.pepGroup.forEach(element => {
          ids.push(element.id);
        })
      }else{
        ids = this.dataform.pepId;
      }
      setTimeout(function() {
        that.$nextTick(() => {
          that.$refs.tree.setCheckedKeys([])
        })

        if (ids.length > 0) {
          that.$nextTick(() => {
            that.$refs.tree.setCheckedKeys(ids)
            if (type == 2) {
              let idList = that.$refs.tree.getCheckedKeys()
              let list = that.$refs.tree.getCheckedNodes()
              that.loadingCheck(idList, list)
            }
          })
        }
      }, 200)


      this.showCheckList = this.dataform.pepGroup;
      this.chooseDialogVisible = true;
    },
    // 单选按钮组切换触发
    adgType(val) {
      if (val == 1) {
        this.dataform.attendanceGroup.offday = [6, 0]
      } else {
        this.dataform.attendanceGroup.offday = [0]
      }
    },
    // 休息日选择
    clickWeek(weekday) {
      if(this.dataform.attendanceGroup.type == 2) {
        let day = weekday[weekday.length - 1];
        if(day == 6 || day == 0) {
          this.dataform.attendanceGroup.offday = [day];
        }else{
          this.$message.error('大小周可选休息日为周六或周日');
          this.dataform.attendanceGroup.offday = [0];
        }
      }
    },
    // 日历渲染
    renderContent(h, parmas) {
      // 设置lunarcalendar=true,parmas返回值包含农历
      // 如果选择是大小周就进loop
      const oneLoop = (data) => {
        if(data.defvalue.type == "normal" || data.defvalue.type == "today") {
          // 判断是单休日是哪天
          if(this.dataform.attendanceGroup.offday[0] == "0") {
            if(data.defvalue.column == "6") {
              let date = getDate(data.defdate);
              let week = Math.ceil(date / 7);
              if(week % 2 == 0) {
                return <div style='background-color: #fff;'>
                  {' '}
                  <div> {data.defvalue.text} </div>
                  <span>上班 </span>
                </div>
              }else{
                return <div style='background-color: #F2F2F2; '>
                  {' '}
                  <div> {data.defvalue.text} </div>
                  <span> 休息 </span>
                </div>
              }
            }
          }else{
            if(data.defvalue.column == "0") {
              let date = getDate(data.defdate);
              let week = Math.ceil(date / 7);
              if(week % 2 == 0) {
                return <div style='background-color: #fff;'>
                  {' '}
                  <div> {data.defvalue.text} </div>
                  <span>上班 </span>
                </div>
              }else{
                return <div style='background-color: #F2F2F2; '>
                  {' '}
                  <div> {data.defvalue.text} </div>
                  <span> 休息 </span>
                </div>
              }
            }
          }
          if(data.defvalue.column == this.dataform.attendanceGroup.offday[0]) {
            return <div style='background-color: #F2F2F2; '>
              {' '}
              <div> {data.defvalue.text} </div>
              <span> 休息 </span>
            </div>
          }

          return <div style='background-color: #fff;'>
            {' '}
            <div> {data.defvalue.text} </div>
            <span>上班 </span>
          </div>
        }else{
          return <div> {data.defvalue.text} </div>
        }
      };
      // 如果选择是固定就进loop2
      const twoLoop = (data) => {
        if(data.defvalue.type == "normal" || data.defvalue.type == "today") {
          for( let i = 0; i < this.dataform.attendanceGroup.offday.length; i++) {
            if(data.defvalue.column == this.dataform.attendanceGroup.offday[i]) {
              return <div style='background-color: #F2F2F2; '>
                {' '}
                <div> {data.defvalue.text} </div>
                <span> 休息 </span>
              </div>
            }
          }
          return <div style='background-color: #fff;'>
            {' '}
            <div> {data.defvalue.text} </div>
            <span>上班 </span>
          </div>
        }else{
          return <div> {data.defvalue.text} </div>
        }
      }
      return <div style='min-height:60px;'> {this.dataform.attendanceGroup.type == 2 ? oneLoop(parmas) : twoLoop(parmas)} </div>

    },
    // 新增编辑考勤组确定设置按钮
    postAttGroup(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          this.$emit('postAttGroup');
          this.$refs["dataform"].resetFields();
          this.dataform.attendanceGroup.id = null;
          this.dataform.attendanceGroup.name = '';
        }else{
          return false;
        }
      });
    },
    // 换组提示弹窗否按钮
    cancelAddTo() {
      if(this.showCheckList.length != 0) {
        this.tipDialog.userIds.forEach(element => {
          for(let i = 0; i< this.showCheckList.length; i++) {
            if(this.showCheckList[i].id == element) {
              this.showCheckList.splice(i, 1);
            }
          }
        })
        this.chooseDialogVisible = false;
      }
      this.changeDialog = false;
    },
    // 多选人员弹窗关闭按钮
    closeStaffDialog() {
      this.chooseDialogVisible = false;
      this.showCheckList = [];
    },
    // 多选人员弹窗下点击人员名单触发事件
    handleCheckChange(data, checked, indeterminate) {
      let ids = this.$refs.tree.getCheckedKeys()
      let list = this.$refs.tree.getCheckedNodes()
      this.loadingCheck(ids, list)
    },
    // 显示选中人员
    loadingCheck(ids, list) {
      let newList = []
      for (let i = 0; i < list.length; i++) {
        if (ids[i] != undefined) {
          const item = {
            id: list[i].id,
            name: list[i].label,
          }
          newList.push(item)
        }
      }
      this.showCheckList = newList
    },
    // 单个已选人员删除按钮
    closeCheckTree(index) {
      let list = []
      this.showCheckList.splice(index, 1)
      list = this.showCheckList
      let ids = []
      for (let i = 0; i < list.length; i++) {
        ids.push(list[i].id)
      }
      this.$refs.tree.setCheckedKeys(ids)
    },
    // 多选人员保存功能
    async postDialog2() {
      let userIds = [];
      if(this.showCheckList.length == 0) {
        this.chooseDialogVisible = false;
        this.dataform.pepId = [];
        return;
      }
      this.showCheckList.forEach( element => {
        userIds.push(element.id);
      })
      let res = await this.$http.post('/group/userExist', {
        userIds,
        id:this.dataform.attendanceGroup.id
      })
      if(res.code == 0 && res.message != "操作成功") {
        this.tipDialog.dialogMsg = res.message;
        this.tipDialog.userIds = res.data;
        this.changeDialog = true;
      }else{
        this.dataform.pepId = [];
        this.dataform.pepGroup = this.showCheckList;
        this.showCheckList.forEach( element => {
          this.dataform.pepId.push(element.id)
        })
        this.changeDialog=false;
        this.chooseDialogVisible = false;
      }
    },
    // 换组提示弹窗是按钮
    determineAdd() {
      this.dataform.pepId = [];
      this.dataform.pepGroup = this.showCheckList;
      this.showCheckList.forEach( element => {
        this.dataform.pepId.push(element.id)
      })
      this.changeDialog=false;
      this.chooseDialogVisible = false;
    }
  },
};
</script>

<style lang="scss">
.bor-rig {
  border-right: 1px #ccc solid;
  padding: 10px;
}

.tree-height {
  height: 250px;
  overflow-y: scroll;
  .show-check {
    padding: 5px 10px;
    margin-top: 5px;
    line-height: 20px;
    background-color: #ccc;
    i {
  float: right;
  line-height: 20px;
}
  }
}

.bor-lef {
  /* border-left: 1px #ccc solid; */
  padding: 10px;
}

.we-bottom-btn{
  margin-bottom: 40px;
  text-align: right;
  .el-button{
    background-color: #4180b1;
  }
}
</style>